﻿import React, { useState } from "react";
import "./App.css";
import "./Calculator.css";

function Calculator() {
  const [materials, setMaterials] = useState([]);
  const [showComparison, setShowComparison] = useState(false);

  const handleAddMaterial = () => {
    setMaterials([
      ...materials,
      {
        selectedMaterial: "",
        transportMode: "",
        distance: "",
        quantity: "",
        calculatedEmissions: null,
      },
    ]);
  };

  const handleMaterialChange = (index, event) => {
    const updatedMaterials = [...materials];
    updatedMaterials[index].selectedMaterial = event.target.value;
    setMaterials(updatedMaterials);
  };

  const handleTransportChange = (index, event) => {
    const updatedMaterials = [...materials];
    updatedMaterials[index].transportMode = event.target.value;
    setMaterials(updatedMaterials);
  };

  const handleDistanceChange = (index, event) => {
    const updatedMaterials = [...materials];
    updatedMaterials[index].distance = event.target.value;
    setMaterials(updatedMaterials);
  };

  const handleQuantityChange = (index, event) => {
    const updatedMaterials = [...materials];
    updatedMaterials[index].quantity = event.target.value;
    setMaterials(updatedMaterials);
  };

  const emissionFactors = {
    concrete_in_situ_unreinforced_c30_37_uk_avg: 0.103,
    concrete_in_situ_unreinforced_c32_40_25_ggbs: 0.12,
    concrete_in_situ_unreinforced_c32_40_50_ggbs: 0.089,
    concrete_in_situ_unreinforced_c32_40_75_ggbs: 0.063,
    concrete_in_situ_unreinforced_c40_50_25_ggbs: 0.138,
    concrete_in_situ_unreinforced_c40_50_50_ggbs: 0.102,
    concrete_in_situ_unreinforced_c40_50_75_ggbs: 0.072,
    concrete_precast_unreinforced_c40_50_uk_avg: 0.178,
    concrete_precast_reinforced_150mm_prestressed_hollow_core_slab: 50.2,
    steel_reinforcement_bars_uk_brc_epd: 0.684,
    steel_reinforcement_bars_worldwide_worldsteel_lci: 1.99,
    steel_pt_strands: 0.684,
    steel_structural_sections_uk_open_sections: 2.45,
    steel_structural_sections_europe_bauforumstahl_avg_epd: 1.13,
    steel_structural_sections_worldwide_worldsteel_lci: 1.55,
    steel_galvanized_profiled_sheet_uk_tata_comflor_epd: 2.74,
    blockwork_precast_concrete_blocks_lightweight: 0.28,
    brick_single_engineering_clay_brick_generic_uk: 0.213,
    timber_manufactured_structural_timber_clt_100_fsc_pefc: 0.437,
    timber_manufactured_structural_timber_glulam_100_fsc_pefc: 0.263,
    timber_studwork_framing_flooring_softwood_100_fsc_pefc: 0.512,
    timber_formwork_plywood_100_fsc_pefc: 0.661,
    plasterboard_partitioning_ceilings_min_60_recycled_content: 0.39,
    intumescent_paint_amotherm_steel_wb: 2.31,
  };

  const wasteFactors = {
    concrete_in_situ_unreinforced_c30_37_uk_avg: 0.053,
    concrete_in_situ_unreinforced_c32_40_25_ggbs: 0.053,
    concrete_in_situ_unreinforced_c32_40_50_ggbs: 0.053,
    concrete_in_situ_unreinforced_c32_40_75_ggbs: 0.053,
    concrete_in_situ_unreinforced_c40_50_25_ggbs: 0.053,
    concrete_in_situ_unreinforced_c40_50_50_ggbs: 0.053,
    concrete_in_situ_unreinforced_c40_50_75_ggbs: 0.053,
    concrete_precast_unreinforced_c40_50_uk_avg: 0.01,
    concrete_precast_reinforced_150mm_prestressed_hollow_core_slab: 0.01,
    steel_reinforcement_bars_uk_brc_epd: 0.053,
    steel_reinforcement_bars_worldwide_worldsteel_lci: 0.053,
    steel_pt_strands: 0.053,
    steel_structural_sections_uk_open_sections: 0.01,
    steel_structural_sections_europe_bauforumstahl_avg_epd: 0.01,
    steel_structural_sections_worldwide_worldsteel_lci: 0.01,
    steel_galvanized_profiled_sheet_uk_tata_comflor_epd: 0.01,
    blockwork_precast_concrete_blocks_lightweight: 0.25,
    brick_single_engineering_clay_brick_generic_uk: 0.25,
    timber_manufactured_structural_timber_clt_100_fsc_pefc: 0.01,
    timber_manufactured_structural_timber_glulam_100_fsc_pefc: 0.01,
    timber_studwork_framing_flooring_softwood_100_fsc_pefc: 0.111,
    timber_formwork_plywood_100_fsc_pefc: 0.111,
    plasterboard_partitioning_ceilings_min_60_recycled_content: 0.29,
    intumescent_paint_amotherm_steel_wb: 0.111,
  };

  const transportEmissionFactors = {
    road: 0.1065,
    sea: 0.01614,
    air: 0.59943,
    rail: 0.02556,
  };

  const handleCalculateClick = (index) => {
    const { selectedMaterial, transportMode, distance, quantity } =
      materials[index];
    const dist = parseFloat(distance);
    const qty = parseFloat(quantity);

    const ecf = emissionFactors[selectedMaterial];
    const tef = transportEmissionFactors[transportMode];
    const wf = wasteFactors[selectedMaterial];

    const a1a3 = ecf * qty;
    const a4 = tef * dist * qty;
    const c2 = 0.005 * qty;
    const c3c4 = selectedMaterial.startsWith("timber") ? 1.77 : 0.013;
    const a5w = wf * (a1a3 + a4 + c2 + c3c4);
    const totalEmissions = a1a3 + a4 + a5w;

    const updatedMaterials = [...materials];
    updatedMaterials[index].calculatedEmissions = {
      ecf: `${ecf} kgCO₂e/kg`,
      tef: `${tef} gCO₂e/kg/km`,
      wf: `${(wf * 100).toFixed(2)}`,
      a1a3: `${a1a3.toFixed(2)} kgCO₂e`,
      a4: `${a4.toFixed(2)} kgCO₂e`,
      c2: `${c2.toFixed(2)} kgCO₂e`,
      c3c4: `${c3c4.toFixed(2)} kgCO₂e/kg`,
      a5w: `${a5w.toFixed(2)} kgCO₂e`,
      totalEmissions: `${totalEmissions.toFixed(2)} kgCO₂e`,
    };
    setMaterials(updatedMaterials);
  };

  return (
    <div className="CalculatorContainer">
      <div className="title">
        <h2>Material Type Calculator</h2>
      </div>

      <div className="mt20">
        <button className="btn btn-primary" onClick={handleAddMaterial}>
          Add Material
        </button>
      </div>

      {materials.map((material, index) => (
        <div key={index} className="itemCon">
          <div className="left con">
            <div className="item">
              <label htmlFor={`material-${index}`}>Select Material:</label>
              <select
                className="select firstSelect"
                id={`material-${index}`}
                value={material.selectedMaterial}
                onChange={(event) => handleMaterialChange(index, event)}
              >
                <option value="">-- Select --</option>
                <optgroup label="Concrete - In situ">
                  <option value="concrete_in_situ_unreinforced_c30_37_uk_avg">
                    Unreinforced, C30/37, UK average ready-mixed concrete EPD
                    (35% cement replacement)
                  </option>
                  <option value="concrete_in_situ_unreinforced_c32_40_25_ggbs">
                    Unreinforced, C32/40, 25% GGBS cement replacement
                  </option>
                  <option value="concrete_in_situ_unreinforced_c32_40_50_ggbs">
                    Unreinforced, C32/40, 50% GGBS cement replacement
                  </option>
                  <option value="concrete_in_situ_unreinforced_c32_40_75_ggbs">
                    Unreinforced, C32/40, 75% GGBS cement replacement
                  </option>
                  <option value="concrete_in_situ_unreinforced_c40_50_25_ggbs">
                    Unreinforced, C40/50, 25% GGBS cement replacement
                  </option>
                  <option value="concrete_in_situ_unreinforced_c40_50_50_ggbs">
                    Unreinforced, C40/50, 50% GGBS cement replacement
                  </option>
                  <option value="concrete_in_situ_unreinforced_c40_50_75_ggbs">
                    Unreinforced, C40/50, 75% GGBS cement replacement
                  </option>
                </optgroup>
                <optgroup label="Concrete - Precast">
                  <option value="concrete_precast_unreinforced_c40_50_uk_avg">
                    Unreinforced, C40/50 with average UK cement mix
                  </option>
                  <option value="concrete_precast_reinforced_150mm_prestressed_hollow_core_slab">
                    Reinforced, 150mm prestressed hollow core slab: British
                    Precast Concrete Federation average EPD
                  </option>
                </optgroup>
                <optgroup label="Steel - Reinforcement Bars">
                  <option value="steel_reinforcement_bars_uk_brc_epd">
                    UK: BRC EPD
                  </option>
                  <option value="steel_reinforcement_bars_worldwide_worldsteel_lci">
                    Worldwide: Worldsteel LCI study data, 2018, world average
                  </option>
                </optgroup>
                <optgroup label="Steel - PT Strands">
                  <option value="steel_pt_strands">
                    (Assume the same as reinforcement bars)
                  </option>
                </optgroup>
                <optgroup label="Steel - Structural Sections">
                  <option value="steel_structural_sections_uk_open_sections">
                    UK open sections: British Steel EPD
                  </option>
                  <option value="steel_structural_sections_europe_bauforumstahl_avg_epd">
                    Europe (excl. UK): Bauforumstahl average EPD
                  </option>
                  <option value="steel_structural_sections_worldwide_worldsteel_lci">
                    Worldwide: Worldsteel LCI study data, 2018, world average
                  </option>
                </optgroup>
                <optgroup label="Steel - Galvanized Profiled Sheet">
                  <option value="steel_galvanized_profiled_sheet_uk_tata_comflor_epd">
                    UK: TATA Comflor EPD
                  </option>
                </optgroup>
                <optgroup label="Blockwork">
                  <option value="blockwork_precast_concrete_blocks_lightweight">
                    Precast concrete blocks, Lightweight blocks
                  </option>
                </optgroup>
                <optgroup label="Brick">
                  <option value="brick_single_engineering_clay_brick_generic_uk">
                    Single engineering clay brick, Generic, UK
                  </option>
                </optgroup>
                <optgroup label="Timber - Manufactured Structural Timber">
                  <option value="timber_manufactured_structural_timber_clt_100_fsc_pefc">
                    CLT, 100% FSC/PEFC
                  </option>
                  <option value="timber_manufactured_structural_timber_glulam_100_fsc_pefc">
                    Glulam, 100% FSC/PEFC
                  </option>
                </optgroup>
                <optgroup label="Timber - Studwork/Framing/Flooring">
                  <option value="timber_studwork_framing_flooring_softwood_100_fsc_pefc">
                    Softwood, 100% FSC/PEFC
                  </option>
                </optgroup>
                <optgroup label="Timber - Formwork">
                  <option value="timber_formwork_plywood_100_fsc_pefc">
                    Plywood, 100% FSC/PEFC
                  </option>
                </optgroup>
                <optgroup label="Plasterboard">
                  <option value="plasterboard_partitioning_ceilings_min_60_recycled_content">
                    Partitioning/ceilings, Minimum 60% recycled content
                  </option>
                </optgroup>
                <optgroup label="Intumescent paint">
                  <option value="intumescent_paint_amotherm_steel_wb">
                    For steelwork, Specific EPD: Amotherm steel WB, Amonn
                  </option>
                </optgroup>
              </select>
            </div>

            <div className="item">
              <label htmlFor={`transport-${index}`}>Transport Mode:</label>
              <select
                className="select"
                id={`transport-${index}`}
                value={material.transportMode}
                onChange={(event) => handleTransportChange(index, event)}
              >
                <option value="">-- Select --</option>
                <option value="road">Road transport</option>
                <option value="sea">Sea transport</option>
                <option value="air">Freight flight</option>
                <option value="rail">Rail transport</option>
              </select>
            </div>

            <div className="item">
              <label htmlFor={`distance-${index}`}>Distance (km):</label>
              <input
                className="input firstInput"
                type="number"
                id={`distance-${index}`}
                value={material.distance}
                onChange={(event) => handleDistanceChange(index, event)}
              />
            </div>

            <div className="item">
              <label htmlFor={`quantity-${index}`}>Quantity (tonnes):</label>
              <input
                className="input SecondInput"
                type="number"
                id={`quantity-${index}`}
                value={material.quantity}
                onChange={(event) => handleQuantityChange(index, event)}
              />
            </div>

            <div className="mt90 btnCon">
              <button
                className="btn btn-primary"
                onClick={() => handleCalculateClick(index)}
              >
                Calculate
              </button>
            </div>
          </div>

          <div className="right con">
            {material.calculatedEmissions && (
              <div className="calcuCon">
                <h3>Embodied carbon per material</h3>
                <p>A1-A3 (Production): {material.calculatedEmissions.a1a3}</p>
                <p>A4 (Transport): {material.calculatedEmissions.a4}</p>
                <p>WF (Waste Factor): {material.calculatedEmissions.wf}</p>
                <p>
                  C2 (Recycling Transport): {material.calculatedEmissions.c2}
                </p>
                <p>C3-C4 (End-of-Life): {material.calculatedEmissions.c3c4}</p>
                <p>A5w (Waste Emissions): {material.calculatedEmissions.a5w}</p>
                <p>
                  Embodied carbon per material:{" "}
                  {material.calculatedEmissions.totalEmissions}
                </p>
              </div>
            )}
          </div>
        </div>
      ))}

      <div className="mt20">
        {materials.length >= 2 && (
          <button
            className="btn btn-primary"
            onClick={() => setShowComparison(!showComparison)}
          >
            {showComparison ? "Hide Comparison" : "Compare Materials"}
          </button>
        )}
      </div>

      {showComparison && (
        <div>
          <h3>Comparison Table</h3>
          <table>
            <thead>
              <tr>
                <th>Material</th>
                <th>A1-A3</th>
                <th>A4</th>
                <th>A5w</th>
                <th>Total Emissions</th>
              </tr>
            </thead>
            <tbody>
              {materials.map((material, index) => (
                <tr key={index}>
                  <td>{material.selectedMaterial}</td>
                  <td>{material.calculatedEmissions.a1a3}</td>
                  <td>{material.calculatedEmissions.a4}</td>
                  <td>{material.calculatedEmissions.a5w}</td>
                  <td>{material.calculatedEmissions.totalEmissions}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

export default Calculator;
